package com.study.student_chuji.demos.service.impl;

import com.study.student_chuji.demos.Mapper.UserMapper;
import com.study.student_chuji.demos.pojo.User;
import com.study.student_chuji.demos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public User findUserWithRoles(Long userId) {
        return userMapper.selectUserRoles(userId);
    }

// 新增用户管理实现
    @Override
    public List<User> findAll() {
        return userMapper.selectAllUsers();
    }

    @Override
    public User findById(Long id) {
        return userMapper.selectById(id);
    }

    @Transactional // 事务保证：用户和角色关联同时成功
    @Override
    public void add(User user, List<Long> roleIds) {
        // 密码加密（默认密码123456）
//        user.setPassword(passwordEncoder.encode("123456"));
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setStatus(1); // 默认启用
        userMapper.insert(user);
        // 关联角色
        if (roleIds != null && !roleIds.isEmpty()) {
            userMapper.batchInsertUserRoles(user.getId(), roleIds);
        }
    }

    @Transactional
    @Override
    public void update(User user, List<Long> roleIds) {
        // 更新用户基本信息（不更新密码）
        userMapper.update(user);
        // 先删后加：更新角色关联
        userMapper.deleteUserRoles(user.getId());
        if (roleIds != null && !roleIds.isEmpty()) {
            userMapper.batchInsertUserRoles(user.getId(), roleIds);
        }
    }

    @Transactional
    @Override
    public void delete(Long id) {
        // 先删角色关联，再删用户
        userMapper.deleteUserRoles(id);
        userMapper.delete(id);
    }
    @Override
    public boolean existsByEmail(String email) {
        return userMapper.countByEmail(email) > 0;
    }
}
